﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.ComponentModel;
using System.Text;
using System.Threading.Tasks;

namespace BlogTruyen.Models
{
    [Table]
    public class Config
    {
        [Column(IsPrimaryKey = true)]
        public string name { get; set; }

        [Column]
        public string value { get; set; }

        public static string GetValue(string name)
        {
            string value = null;

            try
            {
                using (var db = new DbContext())
                {
                    value = db.Configs.Single(t => t.name == name).value;
                }
            }
            catch (Exception) { }
            return value;
        }

        public static void SetValue(string name, string value)
        {
            try
            {
                using (var db = new DbContext())
                {
                    var config = db.Configs.Single(t => t.name == name);
                    config.value = value;
                    db.SubmitChanges();
                }
            }
            catch (Exception) { }
        }

        public static void Init(string name, string value, DbContext db)
        {
            //using (var db = new DbContext())
            //{
                if (db.Configs.Count(t => t.name == name) == 0)
                {
                    db.Configs.InsertOnSubmit(new Config
                    {
                        name = name,
                        value = value
                    });
                    db.SubmitChanges();
                }
            //}
        }
    }
}
